<!--
 生成呈批单
 @Author: zhanbh
 @Date: 2021-04-16
-->
<template>
  <div class="approval-form">
    <div>
      <module-card style="width: 90%">
        <template #header>基本信息</template>
        <edit-form
          class="base-form"
          :model="baseInfo"
          :fields="baseFields"
          :rules="baseRules"
          v-bind="formAttrs"
          ref="form"
        >
          <template #item-fkqk>
            <div v-for="i of baseInfo.fkqk.length" :key="i" class="base-form__fkqk">
              <el-input v-model="baseInfo.fkqk[i - 1]" type="textarea" row="2" placeholder="请输入内容"></el-input>
              <div class="base-form__opers">
                <el-button type="primary" icon="el-icon-plus" circle plain @click="handleAddfkqk()"></el-button>
                <el-button
                  type="primary"
                  icon="el-icon-minus"
                  circle
                  plain
                  :disabled="baseInfo.fkqk.length === 1"
                  @click="handleDelfkqk(i - 1)"
                ></el-button>
              </div>
            </div>
          </template>

          <template #item-fileHolders>
            <dg-upload v-model="baseInfo.fileHolders" :server-url="'./'" size="30m" tip-msg="上传文件限制大小为 30M">
              <el-button type="primary" plain>上传文件</el-button>
              <template slot="fileList" slot-scope="{ type, name, size }">
                <i :class="`dg-icon-${type}`"></i>
                {{ `${name} (${size / 1024})KB` }}
              </template>
            </dg-upload>
          </template>
          <template #item-uploaded>
            <span>无</span>
          </template>
        </edit-form>
      </module-card>
      <module-card style="width: 90%">
        <div class="approval-form__btns">
          <dg-button @click="() => $router.go(-1)">取消</dg-button>
          <dg-button type="primary" @click="handleCreate" :loading="loading">确定</dg-button>
        </div>
      </module-card>
    </div>
  </div>
</template>
<script>
import EditForm from '@@/edit-form';
import ModuleCard from '@/components/layout/module-card';
import { findJrzs, findDrzhz } from '@/api/common';
import { saveApprovalForm, getApprovalFormDetail, updateApprovalForm, jqxxDetail } from '@/api/police';
import { mapState } from 'vuex';
export default {
  name: 'PoliceCommandForm',
  components: {
    EditForm,
    ModuleCard
  },
  props: {},
  data() {
    return {
      jqid: '',
      spdid: '',
      loading: false,
      djrzs: [],
      jrzs: [],
      // 表单通用的配置值
      formAttrs: {
        labelWidth: 'calc(7em + 12px)'
      },

      baseInfo: {
        bt: '',
        bjnr: '',
        cjqk: '',
        fkqk: [''],

        nbyj: '',
        bz: '',
        fileHolders: [],
        drzsCode: '',
        drzhzCode: ''
      },

      baseRules: {
        bt: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        bjnr: [{ required: true, message: '请输入报警内容', trigger: 'blur' }],
        information: [{ required: true, message: '请输入情报支撑', trigger: 'blur' }]
      },

      // 值班
      rosterInfo: {
        depart: '',
        name: ''
      }

      // TODO:21号需求  与需求确认反馈情况测试数据（测试完删掉）
      //   fkqkList: [
      //     {
      //       ypsj: '2021-06-14 10:16:52',
      //       ypdw: '公安局',
      //       ypr: '刘伟',
      //       yplx: '类型1',
      //       ypnr: '这条数据是刘伟研判的哟'
      //     },
      //     {
      //       ypsj: '2021-05-14 10:16:52',
      //       ypdw: '公安局1',
      //       ypr: '丽丽',
      //       yplx: '类型2',
      //       ypnr: '这条数据是丽丽研判的哟'
      //     }
      //   ]
    };
  },
  computed: {
    ...mapState(['constant']),
    baseFields() {
      const vm = this;
      return [
        {
          prop: 'bt',
          label: '标题',
          tag: 'el-input'
        },
        {
          prop: 'bjnr',
          label: '报警内容',
          tag: 'el-input',
          tagBind: {
            type: 'textarea',
            rows: 2,
            placeholder: '请输入内容'
          }
        },
        {
          prop: 'cjqk',
          label: '处警情况',
          tag: 'el-input',
          tagBind: {
            type: 'textarea',
            rows: 2,
            placeholder: '请输入内容'
          }
        },
        {
          prop: 'fkqk',
          label: '反馈情况' //与后端约定输入框大小  TODO:21号需求，与需求确认（反馈情况自动关联研判信息）
        },
        {
          prop: 'nbyj',
          label: '拟办意见',
          tag: 'el-input',
          tagBind: {
            type: 'textarea',
            rows: 2,
            placeholder: '请输入内容'
          }
        },
        {
          prop: 'bz',
          label: '备注',
          tag: 'el-input',
          tagBind: {
            type: 'textarea',
            rows: 2,
            placeholder: '请输入内容'
          }
        },
        {
          prop: 'fileHolders',
          label: '附件'
        },
        {
          prop: 'jrzs',
          label: '当日值守',
          col: 12,
          tag: 'dg-select',
          tagBind: {
            data: vm.jrzs,
            valueName: 'id',
            labelName: 'name'
          }
        },
        {
          prop: 'drzhz',
          label: '今日指挥长',
          col: 12,
          tag: 'dg-select',
          tagBind: {
            data: vm.djrzs,
            valueName: 'id',
            labelName: 'name'
          }
        }
      ];
    },
    isModify() {
      return this.$route.name === 'PoliceApprovalModify';
    }
  },
  methods: {
    /**
     * 获取报警内容、处警情况数据
     */
    getJqDetail() {
      let that_ = this;
      jqxxDetail(that_.jqid).then(({ data }) => {
        let cjxx_list = data.cjxxList; // 处置信息列表
        let cjqk = '';
        // 初始化报警内容
        that_.baseInfo.bjnr = data.bjnr;
        // 初始化处警情况
        if (!_.isEmpty(cjxx_list)) {
          cjxx_list.forEach((item) => {
            let cz_item = `时间：${item.czsj}  `;
            let index_in_dw = _.findIndex(that_.constant.BM_DEPT, { value: item.czdw });
            // 格式化单位
            cz_item += `单位：${that_.constant.BM_DEPT[index_in_dw]['label']}  `;
            // 格式化处置措施
            cz_item += `处置措施：${item.czcs}  `;
            cjqk += `${cz_item};`;
          });
          that_.$set(that_.baseInfo, 'cjqk', cjqk);
        }
      });
    },
    /**
     * 获取反馈情况数据   TODO:21号需求
     */
    // getFkqk() {
    //   let that_ = this;
    //   var fkqk = [];
    //   // 初始反馈情况
    //   if (!_.isEmpty(that_.fkqkList)) {
    //     that_.fkqkList.forEach((item, index) => {
    //       let fkqk_item = `序号：${index + 1}；`;
    //       fkqk_item += `研判时间：${item.ypsj}；`;
    //       fkqk_item += `研判单位：${item.ypdw}；`; // 仿照上面翻译
    //       fkqk_item += `研判人：${item.ypr}；`;
    //       fkqk_item += `研判类型：${item.yplx}；`; // 仿照上面翻译
    //       fkqk_item += `研判内容：${item.ypnr}`;
    //       fkqk[index] = fkqk_item;
    //     });
    //     that_.$set(that_.baseInfo, 'fkqk', fkqk);
    //   }
    // },

    getSpdDetail() {
      getApprovalFormDetail(this.spdid).then(({ data }) => {
        Object.keys(this.baseInfo).forEach((item) => {
          this.baseInfo[item] = data[item];
        });
        if (!this.baseInfo.fkqk.length) {
          this.baseInfo.fkqk.push('');
        }
      });
    },
    /**
     * 创建
     */
    handleCreate() {
      this.$refs.form.$refs.form.validate((valid) => {
        if (valid) {
          const fn = this.spdid ? updateApprovalForm : saveApprovalForm;
          const fkqk = this.baseInfo.fkqk.filter((item) => item !== '');
          fn({
            id: this.spdid,
            jqxxbh: this.$route.params.jqid,
            ...this.baseInfo,
            fkqk
          })
            .then(() => {
              this.loading = false;
              this.$message.success('操作成功');
              this.$router.go(-1);
            })
            .catch(() => {
              this.$message.warning('操作失败');
              this.loading = false;
            });
        }
      });
    },

    /**
     * 添加一条反馈
     * @param index 反馈数组下标
     */
    handleAddfkqk() {
      console.log(455);
      this.baseInfo.fkqk.push('');
    },

    /**
     * 删除一条反馈
     * @param index 反馈数组下标
     */
    handleDelfkqk(index) {
      let { fkqk } = this.baseInfo;
      fkqk.splice(index, 1);
    }
  },
  created() {
    // spdid 有审批单id说明是修改，否则是生成呈批单
    const { name, securityOrgName } = this.$store.state.user.info;
    this.$store.dispatch('getConstant', ['BM_DEPT']);
    if (this.$route.params.spdid) {
      this.spdid = this.$route.params.spdid;
      this.getSpdDetail();
    } else {
      if (this.$route.params.jqid) {
        // 生成呈批单
        this.jqid = this.$route.params.jqid;
        this.getJqDetail();
        // this.getFkqk();
      }
    }

    this.rosterInfo.depart = securityOrgName;
    this.rosterInfo.name = name;
    findJrzs().then(({ data }) => {
      this.jrzs = data;
    });
    findDrzhz().then(({ data }) => {
      this.djrzs = data;
    });
  }
};
</script>
<style scoped lang="scss">
.approval-form {
  > div {
    padding: 12px 20px 1px;
    background: #fff;
    margin-bottom: 12px;
    border-radius: 2px;
  }
  .approval-form__btns {
    margin: 20px;
  }
}
.base-form {
  &__fkqk {
    position: relative;
  }
  &__fkqk + &__fkqk {
    margin-top: 1rem;
  }
  &__opers {
    position: absolute;
    top: 1em;
    right: -5em;

    .el-button {
      padding: 4px;
    }
  }
  &__suggestion /deep/ .el-textarea__inner {
    padding-bottom: 32px;
  }
  &__leader-btn {
    position: absolute;
    bottom: 6px;
    left: 6px;
  }
}
.module-card {
  margin-bottom: 0;
}
</style>
